﻿using Microsoft.Data.Sqlite;
using SSC.Models;

namespace SSC.Services
{
    /// <summary>
    /// 处理对人员管理的增删改查
    /// </summary>
    public class UserService
    {
        public List<UserModel> GetAllUsers()
        {
            // 使用 App.DatabaseService 访问 SQLiteDatabaseService 实例
            string query = "SELECT Id, UserName, UserPassword, UserFace, UserBackup FROM tbUser";
            var users = App.DatabaseService.GetAll<UserModel>(query);
            return users;
        }

        // 新增用户方法
        public void AddUser(UserModel user)
        {
            string query = @"
             INSERT INTO tbUser (
                UserName, 
                UserPassword, 
                UserFace, 
                UserBackup
             ) VALUES (
                @UserName, 
                @UserPassword, 
                @UserFace, 
                @UserBackup
             )";

            bool success = App.DatabaseService.Execute(query, user);
            if (!success)
            {
                throw new Exception("用户新增失败");
            }
        }

        // 更新用户方法
        public void UpdateUser(UserModel user) {
            string query = @"
             UPDATE tbUser 
             SET UserName = @UserName, 
                 UserPassword = @UserPassword, 
                 UserFace = @UserFace, 
                 UserBackup = @UserBackup
             WHERE Id = @Id";

            bool success = App.DatabaseService.Execute(query, user);
            if (!success)
            {
                throw new Exception("用户更新失败");
            }
        }

        // 删除用户方法
        public void DeleteUser(UserModel user)
        {
            string query = "DELETE FROM tbUser WHERE Id = @Id";
            bool success = App.DatabaseService.Execute(query, user);
            if (!success)
            { 
                throw new Exception("用户删除失败");
            }
        }
        //查询用户的方法
        public UserModel QueryUserByName(string username)
        {
            string query = "SELECT UserName, UserPassword, UserFace, UserBackup FROM tbUser WHERE UserName = @UserName";

            // 使用 ExecuteObject 方法获取完整的 UserModel 对象
            return App.DatabaseService.ExecuteObject(query,
                reader => new UserModel
                {
                    UserName = reader["UserName"].ToString(),
                    UserPassword = reader["UserPassword"].ToString(),
                    UserBackup = reader["UserBackup"].ToString(),
                    UserFace = reader["UserFace"].ToString()
                },
                new SqliteParameter("@UserName", username));
        }
    }
}
